package com.chen.authserver.utils;

import com.chen.authserver.bean.TokenConfiguration;
import com.chen.authserver.exception.TokenParseFailureException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class JwtUtils {

    @Autowired
    private TokenConfiguration tokenConfiguration;

    /**
     * 签发JWT
     * @param id
     * @return  String
     *
     */
    public String createToken(String id, String account, String pwd) {
        return createToken( -1, id, account, pwd);
    }

    /**
     * 签发JWT
     * @param id
     * @param ttlMillis
     * @return  String
     *
     */
    public String createToken(long ttlMillis, String id, String account, String pwd) {

        String signatureKey = tokenConfiguration.getSignaturekey();

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //创建payload的私有声明（根据特定的业务需要添加，如果要拿这个做验证，一般是需要和jwt的接收方提前沟通好验证方式的）
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", id);
        claims.put("userAccount", account);
        claims.put("pwd", pwd);
        claims.put("loginTime", now);

        String key = pwd;
        String subject = account;

        JwtBuilder builder = Jwts.builder()
                .setClaims(claims)
                .setId(UUID.randomUUID().toString())
                .setSubject(subject)   // 主题
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, signatureKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }


    /**
     * Token的解密
     * @param token 加密后的token
     * @return
     */
    public Map<String, Object> parseJWT(String token) throws TokenParseFailureException {

        String signatureKey = tokenConfiguration.getSignaturekey();

        try {
            //得到DefaultJwtParser
            Claims claims = Jwts.parser()
                    //设置签名的秘钥
                    .setSigningKey(signatureKey)
                    //设置需要解析的jwt
                    .parseClaimsJws(token).getBody();

            Map<String, Object> ret = new HashMap<>();
            ret.put("id", claims.get("id"));
            ret.put("pwd", claims.get("pwd"));
            ret.put("userAccount", claims.get("userAccount"));
            ret.put("loginTime", claims.get("loginTime"));

            return ret;

        } catch (Exception e) {
            throw new TokenParseFailureException();
        }
    }

//    public static void main(String[] args) throws InterruptedException {
//        String pwd = "123456";
//        String token = createToken("10001", "chenzhuo", pwd);
//        System.out.println("token : " + token);
//
//        Thread.sleep(2000);
//        String token2  = createToken("10001", "chenzhuo", pwd);
//        System.out.println(token.equals(token2));
//
////        String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJDSEVOMTIzNDU2IiwidXNlckFjY291bnQiOiJDSEVOMTIzNDU2IiwiaWQiOiI4IiwicHdkIjoiWFcxQXkzZDlrSFlURUZZVGh0VU42Zz09IiwiaWF0IjoxNTk2Njg4MDU3LCJqdGkiOiI4MjgwYWZiMy1iOWIwLTQxNGYtOTc4NC00ZWQ2NTgxNTY0MDcifQ.pN3JSd_N_5Nfqer8MwgYmtt9JvcepB1F-Z-59mxMXRg";
////        Map<String, Object> ret = null;
////        try {
////            ret = parseJWT(token);
////        } catch (TokenParseFailureException e) {
////            e.printStackTrace();
////        }
////        System.out.println(ret);
//    }
}
